﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Win32;
using Ionic.Zip;
using System.Diagnostics;

namespace Custom_Recommended
{
    public partial class frmMain : Form
    {
        Thread thrGeneral;
        UpdateType utUpdate = UpdateType.NONE;
        PictureBox picEditItem;
        bool blnIdle = true;

        private enum UpdateType
        {
            NONE, AVAILABLE, NEWPATCHER
        }

        public frmMain()
        {
            string ProgramFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
            InitializeComponent();

            if (Custom_Recommended.Properties.Settings.Default.strHoNPath == "")
            {
                RegistryKey regKey;
                regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\hon");

                if (regKey != null)
                {
                    if (Directory.Exists(regKey.GetValue("InstallLocation", ProgramFiles + "\\Heroes of Newerth").ToString()))
                    {
                        Settings.strHoNPath = regKey.GetValue("InstallLocation", ProgramFiles + "\\Heroes of Newerth").ToString();
                    }
                }
                else
                {
                    if (Directory.Exists(ProgramFiles + "\\Heroes of Newerth"))
                    {
                        Settings.strHoNPath = ProgramFiles + "\\Heroes of Newerth";
                    }
                    else
                    {
                        MessageBox.Show("Unable to find the directory path to your Heroes of Newerth, please specify the correct path.");

                        using (FolderBrowserDialog fbd = new FolderBrowserDialog())
                        {
                            fbd.RootFolder = Environment.SpecialFolder.Desktop;
                            fbd.SelectedPath = ProgramFiles + "\\Heroes of Newerth";
                            fbd.ShowNewFolderButton = false;
                            fbd.Description = "Choose the folder in which your Heroes of Newerth is located:";

                            if (fbd.ShowDialog() == DialogResult.OK)
                            {
                                Settings.strHoNPath = fbd.SelectedPath;
                            }
                        }
                    }
                }
            }
            else
            {
                Settings.strHoNPath = Custom_Recommended.Properties.Settings.Default.strHoNPath;
            }

            Settings.blnFolderSaveXML = Custom_Recommended.Properties.Settings.Default.blnFolderSaveXML;
            Settings.intHeroesDisplayed = Custom_Recommended.Properties.Settings.Default.intHeroesDisplayed;
        }

        #region Events
        private void frmMain_Click(object sender, EventArgs e)
        {
            blnIdle = true;
            picFrame.Image = Custom_Recommended.Properties.Resources.Frame;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            WebClient wc;

            if (!File.Exists(Application.StartupPath + "\\crsettings.xml"))
            {
                XmlDocument xmlDocument = new XmlDocument();
                XmlElement crsettings = xmlDocument.CreateElement("crsettings");
                XmlElement heroes = xmlDocument.CreateElement("heroes");
                XmlElement items = xmlDocument.CreateElement("items");
                XmlAttribute version = xmlDocument.CreateAttribute("version");
                XmlAttribute date = xmlDocument.CreateAttribute("date");
                version.Value = Settings.strVersion;
                date.Value = Settings.strDate;

                crsettings.Attributes.Append(version);
                crsettings.Attributes.Append(date);
                crsettings.AppendChild(heroes);
                crsettings.AppendChild(items);
                xmlDocument.AppendChild(crsettings);
                xmlDocument.Save(Application.StartupPath + "\\crsettings.xml");
            }

            // Check for application updates
            thrGeneral = new Thread(delegate() { CheckForUpdates(); });
            thrGeneral.Start();
            thrGeneral.Join();
            thrGeneral = null;

            switch (utUpdate)
            {
                case UpdateType.NEWPATCHER:
                    if (MessageBox.Show(this, "A new update is available, would you like to download it?", "Update Available", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        try
                        {
                            wc = new WebClient();
                            wc.DownloadFile(@"http://dl.dropbox.com/u/2683550/Heroes%20of%20Newerth/Custom%20Recommended/CRUpdater.exe", Application.StartupPath + "\\CRUpdater.exe");
                            while (wc.IsBusy) { };
                            wc.Dispose();
                        }
                        catch (WebException)
                        {
                            MessageBox.Show("Custom Recommended Items was unable to connect to the dropbox server. Please verify your connection to 'http://www.dropbox.com/' try again.");
                        }

                        Process.Start(Application.StartupPath + "\\CRUpdater.exe");
                        Custom_Recommended.Properties.Settings.Default.strHoNPath = Settings.strHoNPath;
                        Custom_Recommended.Properties.Settings.Default.blnFolderSaveXML = Settings.blnFolderSaveXML;
                        Custom_Recommended.Properties.Settings.Default.intHeroesDisplayed = Settings.intHeroesDisplayed;
                        Custom_Recommended.Properties.Settings.Default.Save();
                        Application.Exit();
                    }
                    break;

                case UpdateType.AVAILABLE:
                    if (MessageBox.Show(this, "A new update is available, would you like to download it?", "Update Available", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Process.Start(Application.StartupPath + "\\CRUpdater.exe");
                        Custom_Recommended.Properties.Settings.Default.strHoNPath = Settings.strHoNPath;
                        Custom_Recommended.Properties.Settings.Default.blnFolderSaveXML = Settings.blnFolderSaveXML;
                        Custom_Recommended.Properties.Settings.Default.intHeroesDisplayed = Settings.intHeroesDisplayed;
                        Custom_Recommended.Properties.Settings.Default.Save();
                        Application.Exit();
                    }
                    break;
            }

            // Check for new items
            thrGeneral = new Thread(delegate() { UpdateItemList(); });
            thrGeneral.Start();
            thrGeneral.Join();
            thrGeneral = null;

            // Check for new heroes
            thrGeneral = new Thread(delegate() { UpdateHeroList(); });
            thrGeneral.Start();
            thrGeneral.Join();
            thrGeneral = null;

            // Get hero names
            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlNList;
            xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNList = xmlDoc.SelectNodes("/crsettings/heroes/hero");

            foreach (XmlNode hero in xmlNList)
            {
                cmbHero.Items.Add(hero.Attributes[0].Value);
            }

            // Build item list
            xmlNList = xmlDoc.SelectNodes("/crsettings/items/item");

            foreach (XmlNode item in xmlNList)
            {
                PictureBox picItem = new PictureBox();
                picItem.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + item.Attributes[1].Value + "2.jpg");
                picItem.SizeMode = PictureBoxSizeMode.AutoSize;
                picItem.Margin = new System.Windows.Forms.Padding(0, 0, 21, 21);

                picItem.Tag = item.Attributes["internal"].Value;

                toolTip.SetToolTip(picItem, item.Attributes[0].Value);
                picItem.Click += Item_Click;

                switch (item.Attributes[2].Value)
                {
                    case "Accessories":
                        flowAccessories.Controls.Add(picItem);
                        break;

                    case "Initiation":
                        flowInitiation.Controls.Add(picItem);
                        break;

                    case "Supportive":
                        flowSupportive.Controls.Add(picItem);
                        break;

                    case "Protective":
                        flowProtective.Controls.Add(picItem);
                        break;

                    case "Combative":
                        flowCombative.Controls.Add(picItem);
                        break;

                    case "Morph Attack":
                        flowMorphAttack.Controls.Add(picItem);
                        break;

                    case "Relics":
                        flowRelics.Controls.Add(picItem);
                        break;

                    case "Secret Shop":
                        flowSecretShop.Controls.Add(picItem);
                        break;

                    case "Supplies":
                        flowSupplies.Controls.Add(picItem);
                        break;

                    case "Weapons":
                        flowWeapons.Controls.Add(picItem);
                        break;
                }
            }

            xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");

            cmbHero.Text = cmbHero.Items[0].ToString();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Custom_Recommended.Properties.Settings.Default.strHoNPath = Settings.strHoNPath;
            Custom_Recommended.Properties.Settings.Default.blnFolderSaveXML = Settings.blnFolderSaveXML;
            Custom_Recommended.Properties.Settings.Default.intHeroesDisplayed = Settings.intHeroesDisplayed;
            Custom_Recommended.Properties.Settings.Default.Save();
        }

        private void frmMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (!blnIdle)
                {
                    picEditItem.Image = Image.FromFile(Application.StartupPath + "\\Icons\\Empty_Item.jpg");
                    picEditItem.Tag = "Empty_Item";
                }
            }
        }

        private void cmbHero_SelectedIndexChanged(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlNList;
            xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNList = xmlDoc.SelectNodes("/crsettings/heroes/hero");
            picFrame.Image = Custom_Recommended.Properties.Resources.Frame;
            blnIdle = true;

            foreach (XmlNode hero in xmlNList)
            {
                if (hero.Attributes[0].Value == cmbHero.Text)
                {
                    if (hero.Attributes[2].Value == "true")
                    {
                        chkEnabled.Checked = true;
                    }
                    else
                    {
                        chkEnabled.Checked = false;
                    }

                    picItem1.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[0].InnerText + ".jpg");
                    picItem1.Tag = hero.ChildNodes[0].InnerText;
                    picItem2.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[1].InnerText + ".jpg");
                    picItem2.Tag = hero.ChildNodes[1].InnerText;
                    picItem3.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[2].InnerText + ".jpg");
                    picItem3.Tag = hero.ChildNodes[2].InnerText;
                    picItem4.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[3].InnerText + ".jpg");
                    picItem4.Tag = hero.ChildNodes[3].InnerText;
                    picItem5.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[4].InnerText + ".jpg");
                    picItem5.Tag = hero.ChildNodes[4].InnerText;
                    picItem6.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[5].InnerText + ".jpg");
                    picItem6.Tag = hero.ChildNodes[5].InnerText;
                    picItem7.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[6].InnerText + ".jpg");
                    picItem7.Tag = hero.ChildNodes[6].InnerText;
                    picItem8.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[7].InnerText + ".jpg");
                    picItem8.Tag = hero.ChildNodes[7].InnerText;
                    picItem9.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[8].InnerText + ".jpg");
                    picItem9.Tag = hero.ChildNodes[8].InnerText;
                    picItem10.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[9].InnerText + ".jpg");
                    picItem10.Tag = hero.ChildNodes[9].InnerText;
                    picItem11.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[10].InnerText + ".jpg");
                    picItem11.Tag = hero.ChildNodes[10].InnerText;
                    picItem12.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[11].InnerText + ".jpg");
                    picItem12.Tag = hero.ChildNodes[11].InnerText;
                    picItem13.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[12].InnerText + ".jpg");
                    picItem13.Tag = hero.ChildNodes[12].InnerText;
                    picItem14.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[13].InnerText + ".jpg");
                    picItem14.Tag = hero.ChildNodes[13].InnerText;
                    picItem15.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[14].InnerText + ".jpg");
                    picItem15.Tag = hero.ChildNodes[14].InnerText;
                    picItem16.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[15].InnerText + ".jpg");
                    picItem16.Tag = hero.ChildNodes[15].InnerText;
                    picItem17.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[16].InnerText + ".jpg");
                    picItem17.Tag = hero.ChildNodes[16].InnerText;
                    picItem18.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[17].InnerText + ".jpg");
                    picItem18.Tag = hero.ChildNodes[17].InnerText;
                    picItem19.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[18].InnerText + ".jpg");
                    picItem19.Tag = hero.ChildNodes[18].InnerText;
                    picItem20.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + hero.ChildNodes[19].InnerText + ".jpg");
                    picItem20.Tag = hero.ChildNodes[19].InnerText;
                }
            }
        }

        private void chkEnabled_CheckedChanged(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlNList;
            xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNList = xmlDoc.SelectNodes("/crsettings/heroes/hero");

            foreach (XmlNode hero in xmlNList)
            {
                if (hero.Attributes["name"].Value == cmbHero.Text)
                {
                    hero.Attributes["enabled"].Value = chkEnabled.Enabled.ToString().ToLower();
                    break;
                }
            }

            xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");
        }

        private void Item_Click(object sender, EventArgs e)
        {
            PictureBox picItem = (PictureBox)sender;

            if (!blnIdle)
            {
                picEditItem.Image = Image.FromFile(Application.StartupPath + "\\Icons\\" + picItem.Tag + ".jpg");
                picEditItem.Tag = picItem.Tag;
            }
        }
        #endregion

        #region picItem#.Click
        private void picFrame_Click(object sender, EventArgs e)
        {
            blnIdle = true;
            picFrame.Image = Custom_Recommended.Properties.Resources.Frame;
        }

        private void picItem1_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG1;
            picEditItem = picItem1;
        }

        private void picItem2_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG2;
            picEditItem = picItem2;
        }

        private void picItem3_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG3;
            picEditItem = picItem3;
        }

        private void picItem4_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG4;
            picEditItem = picItem4;
        }

        private void picItem5_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG5;
            picEditItem = picItem5;
        }

        private void picItem6_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG6;
            picEditItem = picItem6;
        }

        private void picItem7_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG7;
            picEditItem = picItem7;
        }

        private void picItem8_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG8;
            picEditItem = picItem8;
        }

        private void picItem9_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG9;
            picEditItem = picItem9;
        }

        private void picItem10_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG10;
            picEditItem = picItem10;
        }

        private void picItem11_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG11;
            picEditItem = picItem11;
        }

        private void picItem12_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG12;
            picEditItem = picItem12;
        }

        private void picItem13_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG13;
            picEditItem = picItem13;
        }

        private void picItem14_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG14;
            picEditItem = picItem14;
        }

        private void picItem15_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG15;
            picEditItem = picItem15;
        }

        private void picItem16_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG16;
            picEditItem = picItem16;
        }

        private void picItem17_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG17;
            picEditItem = picItem17;
        }

        private void picItem18_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG18;
            picEditItem = picItem18;
        }

        private void picItem19_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG19;
            picEditItem = picItem19;
        }

        private void picItem20_Click(object sender, EventArgs e)
        {
            blnIdle = false;
            picFrame.Image = Custom_Recommended.Properties.Resources.FrameG20;
            picEditItem = picItem20;
        }
        #endregion

        #region Menu Strip
        #region File
        private void applyHeroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlNList;
            xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNList = xmlDoc.SelectNodes("/crsettings/heroes/hero");

            foreach (XmlNode hero in xmlNList)
            {
                if (hero.Attributes[0].Value == cmbHero.Text)
                {
                    hero.ChildNodes[0].InnerText = picItem1.Tag.ToString();
                    hero.ChildNodes[1].InnerText = picItem2.Tag.ToString();
                    hero.ChildNodes[2].InnerText = picItem3.Tag.ToString();
                    hero.ChildNodes[3].InnerText = picItem4.Tag.ToString();
                    hero.ChildNodes[4].InnerText = picItem5.Tag.ToString();
                    hero.ChildNodes[5].InnerText = picItem6.Tag.ToString();
                    hero.ChildNodes[6].InnerText = picItem7.Tag.ToString();
                    hero.ChildNodes[7].InnerText = picItem8.Tag.ToString();
                    hero.ChildNodes[8].InnerText = picItem9.Tag.ToString();
                    hero.ChildNodes[9].InnerText = picItem10.Tag.ToString();
                    hero.ChildNodes[10].InnerText = picItem11.Tag.ToString();
                    hero.ChildNodes[11].InnerText = picItem12.Tag.ToString();
                    hero.ChildNodes[12].InnerText = picItem13.Tag.ToString();
                    hero.ChildNodes[13].InnerText = picItem14.Tag.ToString();
                    hero.ChildNodes[14].InnerText = picItem15.Tag.ToString();
                    hero.ChildNodes[15].InnerText = picItem16.Tag.ToString();
                    hero.ChildNodes[16].InnerText = picItem17.Tag.ToString();
                    hero.ChildNodes[17].InnerText = picItem18.Tag.ToString();
                    hero.ChildNodes[18].InnerText = picItem19.Tag.ToString();
                    hero.ChildNodes[19].InnerText = picItem20.Tag.ToString();
                    break;
                }
            }

            xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");
            MessageBox.Show(this, "Hero applied.");
        }

        private void saveXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlDocument xmlSDoc = new XmlDocument();
            XmlNodeList xmlNList;

            XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "");
            XmlElement modification = xmlDoc.CreateElement("modification");
            XmlAttribute application = xmlDoc.CreateAttribute("application");
            XmlAttribute appversion = xmlDoc.CreateAttribute("appversion");
            XmlAttribute mmversion = xmlDoc.CreateAttribute("mmversion");
            XmlAttribute name = xmlDoc.CreateAttribute("name");
            XmlAttribute version = xmlDoc.CreateAttribute("version");
            XmlAttribute date = xmlDoc.CreateAttribute("date");
            XmlAttribute description = xmlDoc.CreateAttribute("description");
            XmlAttribute author = xmlDoc.CreateAttribute("author");
            XmlAttribute weblink = xmlDoc.CreateAttribute("weblink");

            application.Value = "Heroes of Newerth";
            appversion.Value = "*";
            mmversion.Value = "1.3";
            name.Value = "Custom Recommended Items";
            version.Value = Settings.strVersion;
            date.Value = Settings.strDate;
            description.Value = "Edits a hero's entity using an application to create a self-made recommended item list.&#xD;&#xA;&#xD;&#xA;Last Update: " + Settings.strDate;
            author.Value = "Keshoon";
            weblink.Value = @"http://forums.heroesofnewerth.com/showthread.php?p=530035";

            modification.Attributes.Append(application);
            modification.Attributes.Append(appversion);
            modification.Attributes.Append(mmversion);
            modification.Attributes.Append(name);
            modification.Attributes.Append(version);
            modification.Attributes.Append(date);
            modification.Attributes.Append(description);
            modification.Attributes.Append(author);
            modification.Attributes.Append(weblink);
            xmlDoc.AppendChild(declaration);
            xmlDoc.AppendChild(modification);

            xmlSDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNList = xmlSDoc.SelectNodes("/crsettings/heroes/hero");

            foreach (XmlNode hero in xmlNList)
            {
                if (hero.Attributes["enabled"].Value.ToLower() == "true")
                {
                    XmlElement editfile = xmlDoc.CreateElement("editfile");
                    XmlAttribute path = xmlDoc.CreateAttribute("name");
                    path.Value = hero.Attributes["path"].Value;
                    editfile.Attributes.Append(path);

                    XmlElement[] item = new XmlElement[20];
                    XmlElement find = xmlDoc.CreateElement("find");
                    XmlElement find2 = xmlDoc.CreateElement("find");
                    XmlElement insert = xmlDoc.CreateElement("insert");
                    XmlElement insert2 = xmlDoc.CreateElement("insert");
                    XmlAttribute start = xmlDoc.CreateAttribute("position");
                    XmlAttribute end = xmlDoc.CreateAttribute("position");
                    XmlAttribute before = xmlDoc.CreateAttribute("position");
                    XmlAttribute after = xmlDoc.CreateAttribute("position");

                    find.InnerText = "<recommendeditem";
                    find2.InnerText = (char)34 + " />";
                    insert.InnerText = "<!-- ";
                    insert2.InnerText = " -->";
                    start.Value = "start";
                    end.Value = "end";
                    before.Value = "before";
                    after.Value = "after";

                    find.Attributes.Append(start);
                    insert.Attributes.Append(before);
                    find2.Attributes.Append(end);
                    insert2.Attributes.Append(after);

                    modification.AppendChild(editfile);
                    editfile.AppendChild(find);
                    editfile.AppendChild(insert);
                    editfile.AppendChild(find2);
                    editfile.AppendChild(insert2);

                    for (int count = 0; count <= 19; count++)
                    {
                        XmlAttribute after2 = xmlDoc.CreateAttribute("position");
                        after2.Value = "after";

                        item[count] = xmlDoc.CreateElement("insert");
                        item[count].InnerText = "<recommendeditem name=" + (char)34 + hero.ChildNodes[count].InnerText + (char)34 + " />";
                        item[count].Attributes.Append(after2);

                        editfile.AppendChild(item[count]);
                    }
                }
            }

            xmlDoc.Save(Application.StartupPath + "\\mod.xml");
            xmlSDoc.Save(Application.StartupPath + "\\crsettings.xml");

            if (Directory.Exists(Settings.strHoNPath + "\\game\\mods") && Directory.Exists(Settings.strHoNPath))
            {
                if (File.Exists(Application.StartupPath + "\\icon.png") && File.Exists(Application.StartupPath + "\\mod.xml"))
                {
                    if (File.Exists(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod"))
                    {
                        try
                        {
                            File.Delete(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod");
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Custom Recommended Items was unable to properly delete the existing honmod.");
                        }

                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddFile(Application.StartupPath + "\\icon.png", "");
                            zip.AddFile(Application.StartupPath + "\\mod.xml", "");
                            zip.Save(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod");
                        }
                    }
                    else
                    {
                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddFile(Application.StartupPath + "\\icon.png", "");
                            zip.AddFile(Application.StartupPath + "\\mod.xml", "");
                            zip.Save(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod");
                        }
                    }

                    if (File.Exists(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod"))
                    {
                        MessageBox.Show("Success!");
                        Process.Start(Settings.strHoNPath + "\\game\\mods");
                    }
                }
                else if (!File.Exists(Application.StartupPath + "\\icon.png") && File.Exists(Application.StartupPath + "\\mod.xml"))
                {
                    MessageBox.Show("Could not find local 'icon.png'" + Environment.NewLine + "Press OK to redownload it.");
                    WebClient wc = new WebClient();
                    wc.DownloadFile("http://dl.dropbox.com/u/2683550/Heroes%20of%20Newerth/Custom%20Recommended/icon.png", Application.StartupPath + "\\icon.png");
                    while (wc.IsBusy) { Application.DoEvents(); };
                    wc.Dispose();

                    if (File.Exists(Application.StartupPath + "\\icon.png"))
                    {
                        MessageBox.Show("Successfully redownloaded! Please restart the save process.");
                    }
                }
                else if (!File.Exists(Application.StartupPath + "\\mod.xml"))
                {
                    MessageBox.Show("Could not find the generated 'mod.xml'" + Environment.NewLine + "Please restart the save process.");
                }
            }
            else if (!Directory.Exists(Settings.strHoNPath + "\\game\\mods") && File.Exists(Settings.strHoNPath + "\\hon.exe"))
            {
                Directory.CreateDirectory(Settings.strHoNPath + "\\game\\mods");

                if (File.Exists(Application.StartupPath + "\\icon.png") && File.Exists(Application.StartupPath + "\\mod.xml"))
                {
                    if (File.Exists(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod"))
                    {
                        try
                        {
                            File.Delete(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod");
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Custom Recommended Items was unable to properly delete the existing honmod.");
                        }

                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddFile(Application.StartupPath + "\\icon.png", "");
                            zip.AddFile(Application.StartupPath + "\\mod.xml", "");
                            zip.Save(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod");
                        }
                    }
                    else
                    {
                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddFile(Application.StartupPath + "\\icon.png", "");
                            zip.AddFile(Application.StartupPath + "\\mod.xml", "");
                            zip.Save(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod");
                        }
                    }

                    if (File.Exists(Settings.strHoNPath + "\\game\\mods\\customrecommended.honmod"))
                    {
                        MessageBox.Show("Success!");
                        Process.Start(Settings.strHoNPath + "\\game\\mods");
                    }
                }
                else if (!File.Exists(Application.StartupPath + "\\icon.png") && File.Exists(Application.StartupPath + "\\mod.xml"))
                {
                    MessageBox.Show("Could not find local 'icon.png'" + Environment.NewLine + "Press OK to redownload it.");
                    WebClient wc = new WebClient();
                    wc.DownloadFile("http://dl.dropbox.com/u/2683550/Heroes%20of%20Newerth/Custom%20Recommended/icon.png", Application.StartupPath + "\\icon.png");
                    while (wc.IsBusy) { Application.DoEvents(); };
                    wc.Dispose();

                    if (File.Exists(Application.StartupPath + "\\icon.png"))
                    {
                        MessageBox.Show("Successfully redownloaded! Please restart the save process.");
                    }
                }
                else if (!File.Exists(Application.StartupPath + "\\mod.xml"))
                {
                    MessageBox.Show("Could not find the generated 'mod.xml'" + Environment.NewLine + "Please restart the save process.");
                }
            }
        }

        private void resetXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlNList;
            XmlNode xmlNode;

            if (MessageBox.Show(this, "Are you sure you wish to reset ALL heroes to their defaults?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
                xmlNode = xmlDoc.SelectSingleNode("/crsettings/heroes");
                xmlNode.RemoveAll();
                cmbHero.Items.Clear();
                xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");

                thrGeneral = new Thread(delegate() { UpdateHeroList(); });
                thrGeneral.Start();
                thrGeneral.Join();
                thrGeneral = null;

                xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
                xmlNList = xmlDoc.SelectNodes("/crsettings/heroes/hero");

                foreach (XmlNode hero in xmlNList)
                {
                    cmbHero.Items.Add(hero.Attributes[0].Value);
                }

                xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");
                cmbHero.Text = cmbHero.Items[0].ToString();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Custom_Recommended.Properties.Settings.Default.strHoNPath = Settings.strHoNPath;
            Custom_Recommended.Properties.Settings.Default.blnFolderSaveXML = Settings.blnFolderSaveXML;
            Custom_Recommended.Properties.Settings.Default.intHeroesDisplayed = Settings.intHeroesDisplayed;
            Custom_Recommended.Properties.Settings.Default.Save();
            Application.Exit();
        }
        #endregion

        #region Options
        private void browseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string ProgramFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

            using (FolderBrowserDialog fbd = new FolderBrowserDialog())
            {
                fbd.RootFolder = Environment.SpecialFolder.Desktop;
                fbd.SelectedPath = ProgramFiles + "\\Heroes of Newerth";
                fbd.ShowNewFolderButton = false;
                fbd.Description = "Choose the folder in which your Heroes of Newerth is located:";

                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    Settings.strHoNPath = fbd.SelectedPath;
                }
            }
        }

        private void enterManuallyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings.strHoNPath = Microsoft.VisualBasic.Interaction.InputBox("Type the file path WITHOUT the ending \\!" + Environment.NewLine + "Default: C:\\Program Files\\Heroes of Newerth", this.Text, Settings.strHoNPath);
        }

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmImport frmImport = new frmImport();
            if (frmImport.ShowDialog(this) == DialogResult.OK)
            {
                cmbHero.Items.Clear();

                XmlDocument xmlDoc = new XmlDocument();
                XmlNodeList xmlNList;
                xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
                xmlNList = xmlDoc.SelectNodes("/crsettings/heroes/hero");

                foreach (XmlNode hero in xmlNList)
                {
                    cmbHero.Items.Add(hero.Attributes[0].Value);
                }

                xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");
                cmbHero.Text = cmbHero.Items[0].ToString();
            }
        }

        private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmPreferences frmPreferences = new frmPreferences();
            frmPreferences.ShowDialog(this);
        }
        #endregion

        #region Help
        private void instructionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string s1 = "Creating your own recommended item list is simple as 1, 2, 3! Follow these instructions and everything should be fine:" + Environment.NewLine + Environment.NewLine;
            string s2 = "1. Go to 'Options -> Heroes of Newerth Path -> Browse...' and specify the root folder in which your Heroes of Newerth game is located. By default it is 'C:\\Program Files\\Heroes of Newerth\\'." + Environment.NewLine + Environment.NewLine;
            string s3 = "2. Select hero you wish to edit using the dropdown list, then press any of images on the frame to start editing it. To edit one, simply click any item in the tabs." + Environment.NewLine + Environment.NewLine;
            string s4 = "3. Enable the hero by pressing the checkbox and go to 'File -> Apply Hero' (Or press 'CTRL+A') and repeat Step 2 if you wish to add another hero. Otherwise, go to 'File -> Save XML' (or 'CTRL+S') to save your input and create the honmod format." + Environment.NewLine + Environment.NewLine;
            string s5 = "The application SHOULD send a 'Success!' which means you can open up your HoN Modification Manager and apply it to your game!";

            MessageBox.Show(s1 + s2 + s3 + s4 + s5);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Heroes of Newerth Custom Recommended Items by Keshoon" + Environment.NewLine + "Version " + Settings.strVersion);
        }
        #endregion
        #endregion

        #region Functions
        private void UpdateHeroList()
        {
            List<string> CurrentHeroes = new List<string>();
            Dictionary<string, string> HeroTranslations = new Dictionary<string, string>();
            List<string> HeroNames = new List<string>();
            Dictionary<string, string> EntityPaths = new Dictionary<string, string>();
            List<string> HeroesAdded = new List<string>();
            Match match;

            // Get current hero in-game names
            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlNList;
            xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNList = xmlDoc.SelectNodes("/crsettings/heroes/hero");

            foreach (XmlNode hero in xmlNList)
            {
                CurrentHeroes.Add(hero.Attributes[0].Value);
            }

            xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");

            // Extract hero entities and entities_en.str
            using (ZipFile zip = ZipFile.Read(Settings.strHoNPath + "\\game\\resources0.s2z"))
            {
                foreach (ZipEntry entry in zip)
                {
                    match = Regex.Match(entry.FileName, @"heroes/[A-Za-z_]+/hero.entity");

                    if (match.Success)
                    {
                        entry.Extract(ExtractExistingFileAction.OverwriteSilently);
                    }
                    else
                    {
                        match = Regex.Match(entry.FileName, @"heroes/([A-Za-z_]+)/\1.entity");

                        if (match.Success)
                        {
                            entry.Extract(ExtractExistingFileAction.OverwriteSilently);
                        }
                    }
                }

                zip.ExtractSelectedEntries("entities_en.str", ExtractExistingFileAction.OverwriteSilently);
            }

            // Get developer name -> in-game name translations from entities_en.str
            string[] stringtable = File.ReadAllLines(Application.StartupPath + "\\stringtables\\entities_en.str");

            foreach (string line in stringtable)
            {
                match = Regex.Match(line, @"(Hero_[A-Za-z]+)_name\s+(.*)");

                if (match.Success && match.Groups[1].Value != "Hero_Nomad")
                {
                    HeroTranslations.Add(match.Groups[1].Value, match.Groups[2].Value);
                }
            }

            // Read entities for hero developer names
            foreach (string folder in Directory.GetDirectories(Application.StartupPath + "\\heroes"))
            {
                XmlNode xmlNode;

                try
                {
                    xmlDoc.Load(folder + "\\hero.entity");
                    xmlNode = xmlDoc.SelectSingleNode("/hero");
                    HeroNames.Add(xmlNode.Attributes[0].Value);
                    EntityPaths.Add(xmlNode.Attributes[0].Value, folder.Substring(folder.LastIndexOf("\\") - 6) + "\\hero.entity");
                }
                catch
                {
                    xmlDoc.Load(folder + "\\" + folder.Substring(folder.LastIndexOf("\\") + 1) + ".entity");
                    xmlNode = xmlDoc.SelectSingleNode("/hero");
                    HeroNames.Add(xmlNode.Attributes[0].Value);
                    EntityPaths.Add(xmlNode.Attributes[0].Value, folder.Substring(folder.LastIndexOf("\\") - 6) + "\\" + folder.Substring(folder.LastIndexOf("\\") + 1) + ".entity");
                }
            }

            // Compare and add to conversion table
            foreach (KeyValuePair<string, string> hero in HeroTranslations)
            {
                if (!CurrentHeroes.Contains(hero.Value))
                {
                    HeroesAdded.Add(hero.Key);
                }
            }

            // Get current recommended items and add to crsettings.xml
            XmlDocument crsettings = new XmlDocument();
            crsettings.Load(Application.StartupPath + "\\crsettings.xml");

            foreach (string hero in HeroesAdded)
            {
                xmlDoc.Load(EntityPaths[hero]);
                xmlNList = xmlDoc.SelectNodes("/hero/recommendeditem");

                XmlElement element = crsettings.CreateElement("hero");
                XmlAttribute name = crsettings.CreateAttribute("name");
                XmlAttribute path = crsettings.CreateAttribute("path");
                XmlAttribute enabled = crsettings.CreateAttribute("enabled");
                name.Value = HeroTranslations[hero];
                path.Value = EntityPaths[hero];
                enabled.Value = "false";

                for (int count = 0; count <= 20; count++)
                {
                    XmlElement item = crsettings.CreateElement("item");

                    if (xmlNList[count] != null)
                    {
                        item.InnerText = xmlNList[count].Attributes[0].Value;
                    }
                    else
                    {
                        item.InnerText = "Empty_Item";
                    }

                    element.AppendChild(item);
                }

                element.Attributes.Append(name);
                element.Attributes.Append(path);
                element.Attributes.Append(enabled);

                foreach (XmlNode childNode in crsettings.ChildNodes[0].ChildNodes)
                {
                    if (childNode.Name == "heroes")
                    {
                        childNode.AppendChild(element);
                    }
                }
            }

            crsettings.Save(Application.StartupPath + "\\crsettings.xml");
            Directory.Delete(Application.StartupPath + "\\heroes", true);
            Directory.Delete(Application.StartupPath + "\\stringtables", true);
        }

        private void UpdateItemList()
        {
            List<string> CurrentItems = new List<string>();
            Dictionary<string, string> ItemTranslations = new Dictionary<string, string>();
            Dictionary<string, string> Categories = new Dictionary<string, string>();
            List<string> ItemsAdded = new List<string>();
            Match match;

            // Get current item names
            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlNList;
            xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNList = xmlDoc.SelectNodes("/crsettings/items/item");

            foreach (XmlNode item in xmlNList)
            {
                CurrentItems.Add(item.Attributes[0].Value);
            }

            xmlDoc.Save(Application.StartupPath + "\\crsettings.xml");

            // Extract item entities and entities_en.str
            using (ZipFile zip = ZipFile.Read(Settings.strHoNPath + "\\game\\resources0.s2z"))
            {
                foreach (ZipEntry entry in zip)
                {
                    match = Regex.Match(entry.FileName, @"shop_[A-Za-z1-5]+.entity");

                    if (match.Success && entry.FileName != "shop_recommended.entity" && entry.FileName != "shop_outpost.entity")
                    {
                        entry.Extract(ExtractExistingFileAction.OverwriteSilently);
                    }
                }

                zip.ExtractSelectedEntries("entities_en.str", ExtractExistingFileAction.OverwriteSilently);
            }

            // Get internal name translations from entities_en.str
            string[] stringtable = File.ReadAllLines(Application.StartupPath + "\\stringtables\\entities_en.str");

            foreach (string line in stringtable)
            {
                match = Regex.Match(line, @"^(Item_[A-Za-z0-9]+)_name\s+(.*)");

                if (match.Success && match.Groups[1].Value != "Item_Cheese" && match.Groups[1].Value != "Item_NedTomahawk" && match.Groups[1].Value != "Item_Revive" && match.Groups[1].Value != "Item_TokenOfSight" && match.Groups[1].Value != "Item_TokenOfStealth" && match.Groups[1].Value != "Item_SacredGreaves" && match.Groups[1].Value != "Item_FenrirFang")
                {
                    if (match.Groups[1].Value == "Item_Bottle")
                    {
                        ItemTranslations.Add(match.Groups[1].Value, "Bottle");
                    }
                    else
                    {
                        ItemTranslations.Add(match.Groups[1].Value, match.Groups[2].Value);
                    }
                }
            }

            // Read entities for item internal names, compare and add to item list
            XmlDocument crsettings = new XmlDocument();
            crsettings.Load(Application.StartupPath + "\\crsettings.xml");
            if (!Directory.Exists(Application.StartupPath + "\\Icons")) Directory.CreateDirectory(Application.StartupPath + "\\Icons");

            foreach (string entity in Directory.GetFiles(Application.StartupPath + "\\items\\shops"))
            {
                if (entity.EndsWith("shop_outpost.entity"))
                    continue;

                string categoryname = "";

                xmlDoc.Load(entity);
                xmlNList = xmlDoc.SelectNodes("/shop/item");

                switch (xmlDoc.ChildNodes[1].Attributes[0].Value)
                {
                    case "Shop_Accessories":
                        categoryname = "Accessories";
                        break;

                    case "Shop_Recipes1":
                        categoryname = "Initiation";
                        break;

                    case "Shop_Recipes2":
                        categoryname = "Supportive";
                        break;

                    case "Shop_Recipes3":
                        categoryname = "Protective";
                        break;

                    case "Shop_Recipes4":
                        categoryname = "Combative";
                        break;

                    case "Shop_Recipes5":
                        categoryname = "Morph Attack";
                        break;

                    case "Shop_Relics":
                        categoryname = "Relics";
                        break;

                    case "Shop_Secret":
                        categoryname = "Secret Shop";
                        break;

                    case "Shop_Supplies":
                        categoryname = "Supplies";
                        break;

                    case "Shop_Weapons":
                        categoryname = "Weapons";
                        break;
                }

                foreach (XmlNode item in xmlNList)
                {
                    if (!CurrentItems.Contains(ItemTranslations[item.Attributes["name"].Value]))
                    {
                        // Separate one for Bottle because it includes (3/3)
                        if (item.Attributes["name"].Value == "Item_Bottle" && !CurrentItems.Contains("Bottle"))
                        {
                            XmlElement element = crsettings.CreateElement("item");
                            XmlAttribute name = crsettings.CreateAttribute("name");
                            XmlAttribute iname = crsettings.CreateAttribute("internal");
                            XmlAttribute category = crsettings.CreateAttribute("category");
                            name.Value = "Bottle";
                            iname.Value = item.Attributes["name"].Value;
                            category.Value = categoryname;

                            element.Attributes.Append(name);
                            element.Attributes.Append(iname);
                            element.Attributes.Append(category);
                            crsettings.SelectSingleNode("/crsettings/items").AppendChild(element);
                        }
                        else
                        {
                            XmlElement element = crsettings.CreateElement("item");
                            XmlAttribute name = crsettings.CreateAttribute("name");
                            XmlAttribute iname = crsettings.CreateAttribute("internal");
                            XmlAttribute category = crsettings.CreateAttribute("category");
                            name.Value = ItemTranslations[item.Attributes["name"].Value];
                            iname.Value = item.Attributes["name"].Value;
                            category.Value = categoryname;

                            element.Attributes.Append(name);
                            element.Attributes.Append(iname);
                            element.Attributes.Append(category);
                            crsettings.SelectSingleNode("/crsettings/items").AppendChild(element);
                        }

                        WebRequest request;
                        WebResponse response;
                        Stream stream = null;

                        try
                        {
                            request = WebRequest.Create(@"http://www.heroesofnewerth.com/images/items/" + item.Attributes[0].Value + ".jpg");
                            response = request.GetResponse();
                            stream = response.GetResponseStream();
                        }
                        catch (Exception)
                        {

                        }

                        Bitmap image = new Bitmap(stream);
                        Bitmap icon = new Bitmap(60, 60);
                        Graphics graphic = Graphics.FromImage(icon);
                        graphic.DrawImage(image, 0, 0, 60, 60);
                        graphic.Dispose();
                        icon.Save(Application.StartupPath + "\\Icons\\" + item.Attributes["name"].Value + "2.jpg");
                        icon.Dispose();

                        icon = new Bitmap(42, 42);
                        graphic = Graphics.FromImage(icon);
                        graphic.DrawImage(image, 0, 0, 42, 42);
                        graphic.Dispose();
                        icon.Save(Application.StartupPath + "\\Icons\\" + item.Attributes["name"].Value + ".jpg");
                        icon.Dispose();
                    }
                    else if (CurrentItems.Contains(ItemTranslations[item.Attributes["name"].Value]))
                    {
                        if (!File.Exists(Application.StartupPath + "\\Icons\\" + item.Attributes["name"].Value + ".jpg") || !File.Exists(Application.StartupPath + "\\Icons\\" + item.Attributes["name"].Value + "2.jpg"))
                        {
                            WebRequest request;
                            WebResponse response;
                            Stream stream = null;

                            try
                            {
                                request = WebRequest.Create(@"http://www.heroesofnewerth.com/images/items/" + item.Attributes[0].Value + ".jpg");
                                response = request.GetResponse();
                                stream = response.GetResponseStream();
                            }
                            catch (Exception)
                            {

                            }

                            Bitmap image = new Bitmap(stream);
                            Bitmap icon = new Bitmap(60, 60);
                            Graphics graphic = Graphics.FromImage(icon);
                            graphic.DrawImage(image, 0, 0, 60, 60);
                            graphic.Dispose();
                            icon.Save(Application.StartupPath + "\\Icons\\" + item.Attributes["name"].Value + "2.jpg");
                            icon.Dispose();

                            icon = new Bitmap(42, 42);
                            graphic = Graphics.FromImage(icon);
                            graphic.DrawImage(image, 0, 0, 42, 42);
                            graphic.Dispose();
                            icon.Save(Application.StartupPath + "\\Icons\\" + item.Attributes["name"].Value + ".jpg");
                            icon.Dispose();
                        }
                    }
                }

                xmlDoc.Save(entity);
            }

            crsettings.Save(Application.StartupPath + "\\crsettings.xml");
            Directory.Delete(Application.StartupPath + "\\items", true);
            Directory.Delete(Application.StartupPath + "\\stringtables", true);
        }

        private void CheckForUpdates()
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode xmlNode;
            xmlDoc.Load(Application.StartupPath + "\\crsettings.xml");
            xmlNode = xmlDoc.SelectSingleNode("/crsettings");

            try
            {
                WebClient wc = new WebClient();
                wc.DownloadFile(@"http://dl.dropbox.com/u/2683550/Heroes%20of%20Newerth/Custom%20Recommended/version.txt", Application.StartupPath + "\\version.txt");
                while (wc.IsBusy) { };
                wc.Dispose();
            }
            catch (WebException)
            {
                MessageBox.Show("Custom Recommended Items was unable to connect to the dropbox server to check for updates. Please verify your connection to 'http://www.dropbox.com/' try again.");
                return;
            }

            string[] releases = File.ReadAllLines(Application.StartupPath + "\\version.txt");
            string[] version = releases[0].Split('|');
            File.Delete(Application.StartupPath + "\\version.txt");

            if (version[0].StartsWith("@"))
            {
                if (new Version(version[0].Substring(1)) > new Version(Settings.strVersion))
                {
                    utUpdate = UpdateType.NEWPATCHER;
                }
            }
            else
            {
                if (new Version(version[0]) > new Version(Settings.strVersion))
                {
                    utUpdate = UpdateType.AVAILABLE;

                    foreach (string release in releases)
                    {
                        if (release.StartsWith("@"))
                        {
                            if (new Version(release.Substring(1, release.IndexOf('|') - 1)) > new Version(Settings.strVersion))
                            {
                                utUpdate = UpdateType.AVAILABLE;
                                break;
                            }
                        }
                    }
                }
            }
        }
        #endregion
    }

    public static class Settings
    {
        public const string strVersion = "3.2.1";
        public const string strDate = "4.10.2011";
        public static string strHoNPath;

        public static bool blnFolderSaveXML;
        public static int intHeroesDisplayed;
    }
}